package com.bsj.travel.config.redis;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.bsj.JedisClusterBSJ;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @author yinhao
 * @description redis集群配置
 * @date 2023/10/18
 */
@Slf4j
@RefreshScope
@Configuration
public class JedisConfig {
    @Value("${redis.host}")
    public String host;
    @Value("${redis.port}")
    public Integer port;
    @Value("${redis.password}")
    public String password;
    @Value("${redis.maxIdle}")
    public Integer maxIdle;
    @Value("${redis.maxTotal}")
    public Integer maxTotal;
    @Value("${redis.maxWaitMillis}")
    public Integer maxWaitMillis;
    @Value("${redis.parallelNum}")
    public Integer parallelNum;

    private static final int DEFAULT_TIMEOUT = 2000;
    private static final int DEFAULT_MAX_REDIRECTIONS = 5;

    @Bean
    public JedisClusterBSJ jedisClusterBSJ() {
        JedisPoolConfig config = new JedisPoolConfig();
        Set<HostAndPort> nodes = new HashSet<>();
        String[] hostArr = host.split(";");
        for (String host : hostArr) {
            nodes.add(new HostAndPort(host, port));
        }
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxIdle(maxIdle);
        log.info("redis配置：host={},port={}", host, port);
        return new JedisClusterBSJ(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, password,
                config, parallelNum);
    }
}
